package main

import (
	"supply-chain/handlers"
	"supply-chain/models"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

func main() {
	// 初始化数据库
	db, err := gorm.Open(sqlite.Open("supply_chain.db"), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	// 自动迁移数据库结构
	db.AutoMigrate(&models.Material{}, &models.Product{})

	// 初始化处理器
	supplierHandler := &handlers.SupplierHandler{DB: db}
	manufacturerHandler := &handlers.ManufacturerHandler{DB: db}
	dealerHandler := &handlers.DealerHandler{DB: db}

	// 初始化路由
	r := gin.Default()

	// 设置路由组
	supplier := r.Group("/supplier")
	manufacturer := r.Group("/manufacturer")
	dealer := r.Group("/dealer")

	// 注册路由处理函数
	registerSupplierRoutes(supplier, supplierHandler)
	registerManufacturerRoutes(manufacturer, manufacturerHandler)
	registerDealerRoutes(dealer, dealerHandler)

	// 启动服务器
	r.Run(":8080")
}

func registerSupplierRoutes(r *gin.RouterGroup, h *handlers.SupplierHandler) {
	r.POST("/materials", h.CheckInMaterial)
	r.GET("/materials/:epc_id", h.GetMaterial)
}

func registerManufacturerRoutes(r *gin.RouterGroup, h *handlers.ManufacturerHandler) {
	r.POST("/products", h.RequestMaterial)
	r.GET("/products/:epc_id", h.GetProduct)
}

func registerDealerRoutes(r *gin.RouterGroup, h *handlers.DealerHandler) {
	r.POST("/products", h.RequestProduct)
	r.GET("/products/:epc_id/trace", h.GetProductTrace)
}

